package com.junzhiit.nengji.cms.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.junzhiit.nengji.bo.ChainGoodsBO;
import com.junzhiit.nengji.bo.ChainGoodsListBO;
import com.junzhiit.nengji.bo.ChainGoodsSkuItemsBO;
import com.junzhiit.nengji.bo.GoodsSkuItemsBO;
import com.junzhiit.nengji.cms.service.ChainGoodsService;
import com.junzhiit.nengji.cms.web.exception.BrandNotFoundException;
import com.junzhiit.nengji.cms.web.exception.ChainAuditFailedException;
import com.junzhiit.nengji.cms.web.exception.ChainAuditWaitException;
import com.junzhiit.nengji.cms.web.exception.ChainGoodsNotFoundException;
import com.junzhiit.nengji.cms.web.exception.ChainNotFoundException;
import com.junzhiit.nengji.cms.web.exception.GoodsStatusErrorException;
import com.junzhiit.nengji.cms.web.exception.ShopNotChainException;
import com.junzhiit.nengji.cms.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.cms.web.exception.TypeNotFoundException;
import com.junzhiit.nengji.cms.web.util.Constants;
import com.junzhiit.nengji.cms.web.util.OrderNumberUtils;
import com.junzhiit.nengji.cms.web.util.ViewObjectUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.cms.web.vo.ChainGoodsAddVO;
import com.junzhiit.nengji.cms.web.vo.ChainGoodsDetailsVO;
import com.junzhiit.nengji.cms.web.vo.ChainGoodsEditVO;
import com.junzhiit.nengji.cms.web.vo.ChainGoodsListVO;
import com.junzhiit.nengji.cms.web.vo.ChainGoodsSkuItemsDetailVO;
import com.junzhiit.nengji.cms.web.vo.ChainGoodsSkuItemsVO;
import com.junzhiit.nengji.cms.web.vo.ChainGoodsTransformVO;
import com.junzhiit.nengji.cms.web.vo.DataTablesParamVO;
import com.junzhiit.nengji.cms.web.vo.GoodsSkuItemsDetailVO;
import com.junzhiit.nengji.cms.web.vo.GoodsSkuItemsVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.dao.BrandDAO;
import com.junzhiit.nengji.dao.ChainBrandDAO;
import com.junzhiit.nengji.dao.ChainDAO;
import com.junzhiit.nengji.dao.ChainGoodsDAO;
import com.junzhiit.nengji.dao.ChainGoodsImagesDAO;
import com.junzhiit.nengji.dao.ChainGoodsSkuItemsDAO;
import com.junzhiit.nengji.dao.ChainGoodsSystemTypeDAO;
import com.junzhiit.nengji.dao.ChainSkuContentDAO;
import com.junzhiit.nengji.dao.ChainSkuDAO;
import com.junzhiit.nengji.dao.ChainSkuItemsDAO;
import com.junzhiit.nengji.dao.ChainTypeDAO;
import com.junzhiit.nengji.dao.GoodsDAO;
import com.junzhiit.nengji.dao.GoodsImagesDAO;
import com.junzhiit.nengji.dao.GoodsSkuItemsDAO;
import com.junzhiit.nengji.dao.GoodsSystemTypeDAO;
import com.junzhiit.nengji.dao.ModulesGoodsDAO;
import com.junzhiit.nengji.dao.ShopChainGoodsDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.SkuContentDAO;
import com.junzhiit.nengji.dao.SkuDAO;
import com.junzhiit.nengji.dao.SkuItemsDAO;
import com.junzhiit.nengji.dao.TypeDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Brand;
import com.junzhiit.nengji.model.Chain;
import com.junzhiit.nengji.model.ChainBrand;
import com.junzhiit.nengji.model.ChainGoods;
import com.junzhiit.nengji.model.ChainGoodsImages;
import com.junzhiit.nengji.model.ChainGoodsSystemType;
import com.junzhiit.nengji.model.ChainSku;
import com.junzhiit.nengji.model.ChainSkuContent;
import com.junzhiit.nengji.model.ChainSkuItems;
import com.junzhiit.nengji.model.ChainType;
import com.junzhiit.nengji.model.Goods;
import com.junzhiit.nengji.model.GoodsImages;
import com.junzhiit.nengji.model.GoodsSkuItems;
import com.junzhiit.nengji.model.GoodsSystemType;
import com.junzhiit.nengji.model.ModulesGoods;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.ShopChainGoods;
import com.junzhiit.nengji.model.Sku;
import com.junzhiit.nengji.model.SkuContent;
import com.junzhiit.nengji.model.SkuItems;
import com.junzhiit.nengji.model.Type;
import com.junzhiit.nengji.model.enums.ChainGoodsStatus;
import com.junzhiit.nengji.model.enums.GoodsStatus;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.LoginType;
import com.junzhiit.nengji.model.enums.PostageType;

@Service
public class ChainGoodsServiceImpl extends BaseServiceImpl implements ChainGoodsService{
	
	@Value("${upload.mall.chain.goods}")
	private String chainGoodsPath;

	@Value("${upload.mall.goods}")
	private String goodsPath;
	
	
	@Autowired
	private ChainGoodsDAO chainGoodsDAO; 
	
	@Autowired
	private ChainDAO chainDAO;
	
	@Autowired
	private ChainGoodsSystemTypeDAO chainGoodsSystemTypeDAO;
	
	@Autowired
	private GoodsSystemTypeDAO goodsSystemTypeDAO;
	
	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;
	
	@Autowired
	private ShopDAO shopDAO;
	
	@Autowired
	private GoodsDAO goodsDAO;

	@Autowired
	private ChainGoodsSkuItemsDAO chainGoodsSkuItemsDAO;
	
	@Autowired
	private ChainSkuDAO chainSkuDAO;
	
	@Autowired
	private SkuDAO skuDAO;
	
	@Autowired
	private ChainSkuItemsDAO chainSkuItemsDAO;
	
	@Autowired
	private SkuItemsDAO skuItemsDAO;
	
	@Autowired
	private ChainSkuContentDAO chainSkuContentDAO;
	
	@Autowired
	private SkuContentDAO skuContentDAO;
	
	@Autowired
	private GoodsSkuItemsDAO goodsSkuItemsDAO;
	
	
	@Autowired
	private ChainGoodsImagesDAO chainGoodsImagesDAO;
	
	@Autowired
	private GoodsImagesDAO goodsImagesDAO;
	
	@Autowired
	private ModulesGoodsDAO modulesGoodsDAO;
	
	@Autowired
	private ShopChainGoodsDAO shopChainGoodsDAO;
	
	@Autowired
	private ChainBrandDAO chainBrandDAO;
	
	@Autowired
	private BrandDAO brandDAO;
	
	@Autowired
	private ChainTypeDAO chainTypeDAO;
	
	@Autowired
	private TypeDAO typeDAO;
	
	@Override
	public ResultVO add(ChainGoodsAddVO chainGoodsAddVO){
		ResultVO result=new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(chainGoodsAddVO.getSessionId()), SystemUserSessionVO.class);
		Chain chain= chainDAO.query(systemUserSessionVO.getSystemId());
		if (chain == null) {
			throw new ChainNotFoundException("连锁品牌不存在");
		}
		
		//判断返利是否在范围内
		int isOpenRebate=chainGoodsAddVO.getIsOpenRebate();
//		if(isOpenRebate==1){
//			
//		}
			

		String maxCode = chainGoodsDAO.queryMaxCode();
		String code = Integer.toString(Integer.parseInt(maxCode) + 1);
		Integer discount = chainGoodsAddVO.getDiscount();
		if (discount == null) {
			chainGoodsAddVO.setDiscount(0);
		}
		chainGoodsAddVO.setCode(code);
		chainGoodsAddVO.setChainId(chain.getId());
		chainGoodsAddVO.setStatus(GoodsStatus.AUDIT.toIntStatus());
		if(chainGoodsAddVO.getPostageType()==PostageType.POSTAGE.toIntValue()){
			chainGoodsAddVO.setPostagePrice(0.00);
		}

		ChainGoods chainGoods = new ChainGoods();
		BeanUtils.copyProperties(chainGoodsAddVO, chainGoods);
		ChainGoods data = chainGoodsDAO.insert(chainGoods);

		//goodsSystemType
		if(StringUtils.isNoneBlank(data.getId())){
			List<ChainGoodsSystemType> list = new ArrayList<ChainGoodsSystemType>();
			for(int i = 0;i<chainGoodsAddVO.getSystemTypeId().size();i++){
				ChainGoodsSystemType chainGoodsSystemType = new ChainGoodsSystemType();
				chainGoodsSystemType.setChainGoodsId(data.getId());
				chainGoodsSystemType.setSystemTypeId(chainGoodsAddVO.getSystemTypeId().get(i));
				chainGoodsSystemType.setCreatedTime(new Date());
				list.add(chainGoodsSystemType);
			}
			chainGoodsSystemTypeDAO.batchInsert(list);
		}
		
		result.setData(data);
		
		return result;
	}
	
	@Override
	public ResultVO edit(ChainGoodsEditVO chainGoodsEditVO) {

		ResultVO result = new ResultVO();
		ChainGoods chainGoods = new ChainGoods();
		if(chainGoodsEditVO.getPostageType()==PostageType.POSTAGE.toIntValue()){
			chainGoodsEditVO.setPostagePrice(0.00);
		}
		BeanUtils.copyProperties(chainGoodsEditVO, chainGoods);
		chainGoods.setStatus(GoodsStatus.AUDIT.toIntStatus());
		
		boolean data = chainGoodsDAO.update(chainGoods);
		//goodsSystemType
		if(StringUtils.isNoneBlank(chainGoodsEditVO.getId())){
			
			chainGoodsSystemTypeDAO.deleteByChainGoodsId(chainGoodsEditVO.getId());
			
			List<ChainGoodsSystemType> list = new ArrayList<ChainGoodsSystemType>();
			for(int i = 0;i<chainGoodsEditVO.getSystemTypeId().size();i++){
				ChainGoodsSystemType chainGoodsSystemType = new ChainGoodsSystemType();
				chainGoodsSystemType.setChainGoodsId(chainGoodsEditVO.getId());
				chainGoodsSystemType.setSystemTypeId(chainGoodsEditVO.getSystemTypeId().get(i));
				chainGoodsSystemType.setCreatedTime(new Date());
				list.add(chainGoodsSystemType);
			}
			chainGoodsSystemTypeDAO.batchInsert(list);
		}
		
		result.setData(data);
		
		return result;
	}
	
	@Override
	public Map<String, Object> findPageAll(DataTablesParamVO dtp, ChainGoodsListVO chainGoodsListVO) {

		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(chainGoodsListVO.getSessionId()), SystemUserSessionVO.class);
		ChainGoods chainGoods=new ChainGoods();
		BeanUtils.copyProperties(chainGoodsListVO, chainGoods);
		if(systemUserSessionVO.getLoginType() != LoginType.INTERNAL.toIntType()){
			Chain chain= chainDAO.query(systemUserSessionVO.getSystemId());
			if (chain == null) {
				throw new ChainNotFoundException("连锁品牌不存在");
			}
			chainGoods.setChainId(chain.getId());
		}
		List<ChainGoodsBO> list = chainGoodsDAO.findPageAll(chainGoods, dtp.getStart(), dtp.getLength(),chainGoodsListVO.getCheckType());
		int totalCount = chainGoodsDAO.getTotalCount(chainGoods,chainGoodsListVO.getCheckType());
		return ViewObjectUtil.dataTables(list, dtp.getDraw(), totalCount);
	}
	
	
	@Override
	public ResultVO findByIdForOther(String id) {
		ResultVO result = new ResultVO();
		ChainGoodsBO chainGoodsBO = chainGoodsDAO.findByIdForOther(id);
		if (chainGoodsBO == null) {
			throw new ChainGoodsNotFoundException("商品不存在");
		}
		result.setData(chainGoodsBO);
		return result;
	}

	@Override
	public ResultVO findById(String id) {
		ResultVO result = new ResultVO();
		ChainGoods chainGoods = chainGoodsDAO.query(id);
		if (chainGoods == null) {
			throw new ChainGoodsNotFoundException("连锁品牌商品不存在");
		}
		
		ChainGoodsDetailsVO vo=new ChainGoodsDetailsVO();
		BeanUtils.copyProperties(chainGoods, vo);
		List<String> systemTypes = chainGoodsSystemTypeDAO.getGoodsSystemTypeByChainGoodsId(chainGoods.getId());
		vo.setSystemTypeId(systemTypes);
		result.setData(vo);
		return result;
	}
	
	@Override
	public ResultVO batchUpdateStatus(String[] ids, Integer status,String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
		if (chain == null) {
			throw new ChainNotFoundException("连锁品牌不存在");
		}
		
		if(chain.getAuditStatus()==0){
			throw new ChainAuditWaitException("店铺等待审核中");
		}
		
		if(chain.getAuditStatus()==1){
			throw new ChainAuditFailedException("店铺审核未通过");
		}
		
		if (ids.length <= 0) {
			return result;
		}

		if (status != ChainGoodsStatus.INACTIVE.toIntStatus() && status != ChainGoodsStatus.ACTIVE.toIntStatus()) {
			return result;
		}
		boolean data = false;
		if (status == ChainGoodsStatus.ACTIVE.toIntStatus()) {
			data = chainGoodsDAO.batchUpdateStatus(ids, GoodsStatus.ACTIVE.toIntStatus());
		} else if (status == ChainGoodsStatus.INACTIVE.toIntStatus()) {
			data = chainGoodsDAO.batchUpdateStatus(ids, GoodsStatus.INACTIVE.toIntStatus());
		}
		result.setData(data);
		return result;
	}
	
	
	@Override
	public ResultVO updateStatus(String id, Integer status,String sessionId) {
		ResultVO result = new ResultVO();
		
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
		if (chain == null) {
			throw new ChainNotFoundException("连锁品牌不存在");
		}
		
		if(chain.getAuditStatus()==0){
			throw new ChainAuditWaitException("店铺等待审核中");
		}
		
		if(chain.getAuditStatus()==1){
			throw new ChainAuditFailedException("店铺审核未通过");
		}
		

		ChainGoods chainGoods=chainGoodsDAO.query(id);
		if (chainGoods == null) {
			throw new ChainGoodsNotFoundException("商品不存在");
		}

		if (status != ChainGoodsStatus.ACTIVE.toIntStatus() && status != ChainGoodsStatus.INACTIVE.toIntStatus() &&status != ChainGoodsStatus.AUDIT.toIntStatus()) {
			return result;
		}

		boolean data = false;
		if (status == GoodsStatus.ACTIVE.toIntStatus()) {
			data = chainGoodsDAO.updateStatus(id, GoodsStatus.ACTIVE.toIntStatus());
		} else if (status == GoodsStatus.INACTIVE.toIntStatus()) {
			data = chainGoodsDAO.updateStatus(id, GoodsStatus.INACTIVE.toIntStatus());
		} else if(status == GoodsStatus.AUDIT.toIntStatus()){
			data = chainGoodsDAO.updateStatus(id, GoodsStatus.AUDIT.toIntStatus());
		}
		result.setData(data);

		return result;
	}
	
	@Transactional
	@Override
	public ResultVO delete(String id) {
		ResultVO result = new ResultVO();
		//商品删除
		chainGoodsDAO.updateToDelete(id);
		return result;
	}
	
	
	@Override
	public Map<String, Object> findByChainId(DataTablesParamVO dtp,ChainGoodsListVO chainGoodsListVO){
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(chainGoodsListVO.getSessionId()), SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		ChainGoodsListBO chainGoodsListBO=new ChainGoodsListBO();
		BeanUtils.copyProperties(chainGoodsListVO, chainGoodsListBO);
		if(shop.getIsChain()==Is.NO.toIntValue()){
			throw new ShopNotChainException("店铺不属于连锁品牌");
		}
		chainGoodsListBO.setChainId(shop.getChainId());
		chainGoodsListBO.setShopId(shop.getId());
		List<ChainGoodsBO> list = chainGoodsDAO.findPageAll(chainGoodsListBO, dtp.getStart(), dtp.getLength());
		int totalCount = chainGoodsDAO.getTotalCount(chainGoodsListBO);
		
		return ViewObjectUtil.dataTables(list, dtp.getDraw(), totalCount);
	}
	
	@Transactional
	@Override
	public ResultVO importChainGoods(ChainGoodsTransformVO chainGoodsTransformVO){
		ResultVO result=new ResultVO();
		
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(chainGoodsTransformVO.getSessionId()), SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		
		ChainGoods chainGoods=chainGoodsDAO.query(chainGoodsTransformVO.getId());
		if(chainGoods==null){
			throw new ChainGoodsNotFoundException("商品未找到");
		}
		
		//brand
		ChainBrand chainBrand=chainBrandDAO.query(chainGoods.getChainBrandId());
		if(chainBrand==null){
			throw new BrandNotFoundException("品牌未找到");
		}
		Brand newBrand;
		Brand brand=new Brand();
		brand.setShopId(shop.getId());
		brand.setName(chainBrand.getName());
		int brandCount=brandDAO.getBrandExist(brand);
		if(brandCount<=0){
			BeanUtils.copyProperties(chainBrand, brand,Constants.BASE_FIELD);
			newBrand=brandDAO.insert(brand);
		}else{
			newBrand=brandDAO.getBrand(brand);
		}
		
		//type
		ChainType chainType=chainTypeDAO.query(chainGoods.getChainTypeId());
		Type newType=new Type();
		Type param=new Type();
		
		if(Constants.ROOT_VALUE.equals(chainType.getParentId())){
			BeanUtils.copyProperties(chainType, param);
			param.setParentId(Constants.ROOT_VALUE);
		}else{
			ChainType parentChainType=chainTypeDAO.query(chainType.getParentId());
			
			Type newParentType=new Type();
			Type parentParam=new Type();
			
			if(Constants.ROOT_VALUE.equals(chainType.getParentId())){
				BeanUtils.copyProperties(parentChainType, parentParam);
				parentParam.setParentId(Constants.ROOT_VALUE);
			}else{
				ChainType rootChainType=chainTypeDAO.query(parentChainType.getId());
				
				Type newRootType=new Type();
				Type rootParam=new Type();
				BeanUtils.copyProperties(rootChainType, rootParam);
				rootParam.setShopId(shop.getId());
				newRootType=addType(rootParam);
				
				BeanUtils.copyProperties(parentChainType, newRootType);
				newParentType.setParentId(newRootType.getId());
				
			}
			parentParam.setName(parentChainType.getName());
			parentParam.setShopId(shop.getId());
			newParentType=addType(parentParam);
			
			param.setParentId(newParentType.getId());
		}
		
		param.setName(chainType.getName());
		param.setShopId(shop.getId());
		newType=addType(param);
		
		//goods
		Goods goods=new Goods();
		BeanUtils.copyProperties(chainGoods, goods,Constants.BASE_FIELD);
		String maxCode = goodsDAO.queryMaxCode();
		String code = Integer.toString(Integer.parseInt(maxCode) + 1);
		goods.setShopId(shop.getId());
		goods.setCode(code);
		goods.setUpdatedTime(new Date());
		goods.setBrandId(newBrand.getId());
		goods.setTypeId(newType.getId());
		goods.setStatus(GoodsStatus.AUDITSUCCESS.toIntStatus());
		goods.setIsChainImport(Is.YES.toIntValue());
		Goods newGoods=goodsDAO.insert(goods);
		
		//goods_system_type
		List<ChainGoodsSystemType> chainGoodsSystemTypeList=chainGoodsSystemTypeDAO.findByChainGoodsId(chainGoods.getId());
		List<GoodsSystemType> goodsSystemTypeList=new ArrayList<GoodsSystemType>();
		for(ChainGoodsSystemType chainGoodsSystemType:chainGoodsSystemTypeList){
			GoodsSystemType goodsSystemType=new GoodsSystemType();
			goodsSystemType.setGoodsId(newGoods.getId());
			goodsSystemType.setSystemTypeId(chainGoodsSystemType.getSystemTypeId());
			goodsSystemType.setCreatedTime(new Date());
			goodsSystemTypeList.add(goodsSystemType);
		}
		
		goodsSystemTypeDAO.batchInsert(goodsSystemTypeList);
		
		//goodsSkuItems
		List<ChainGoodsSkuItemsBO> chainGoodsSkuItemsBOList=chainGoodsSkuItemsDAO.queryGoodsSkuItemsBO(chainGoods.getId());
		Collection<ChainGoodsSkuItemsVO> ChainGoodsSkuItemsVOList=this.oneToManyByChainGoods(chainGoodsSkuItemsBOList);
		
		//goods_sku_items
		List<GoodsSkuItems> goodsSkuItemsList=new ArrayList<GoodsSkuItems>();
		for(ChainGoodsSkuItemsVO chainGoodsSkuItemsVO:ChainGoodsSkuItemsVOList){
			//sku
			ChainSku chainSku=chainSkuDAO.query(chainGoodsSkuItemsVO.getChainSkuId());
			Sku sku=new Sku();
			BeanUtils.copyProperties(chainSku, sku);
			sku.setShopId(shop.getId());
			int skuExistCount=skuDAO.queryNameIsExit(sku.getShopId(), sku.getName());
			Sku newSku=new Sku();
			if(skuExistCount<=0){
				newSku=skuDAO.insert(sku);
			}
			
			newSku=skuDAO.findSkuByName(sku.getShopId(),sku.getName());
			
			for(ChainGoodsSkuItemsDetailVO chainGoodsSkuItemsDetailVO:chainGoodsSkuItemsVO.getChildrens()){
				//sku_items
				ChainSkuItems chainSkuItems=chainSkuItemsDAO.query(chainGoodsSkuItemsDetailVO.getChainSkuItemsId());
				
				SkuItems skuItems=new SkuItems();
				BeanUtils.copyProperties(chainSkuItems, skuItems);
				skuItems.setSkuId(newSku.getId());
				SkuItems newSkuItems=new SkuItems();
				int skuItemsExistCount=skuItemsDAO.queryNameIsExit(skuItems.getSkuId(), skuItems.getStandard());
				if(skuItemsExistCount<=0){
					newSkuItems=skuItemsDAO.insert(skuItems);
				}
				newSkuItems=skuItemsDAO.findSkuItemsByStandard(skuItems.getSkuId(),skuItems.getStandard());
				
				//goods_sku_items
				GoodsSkuItems goodsSkuItems=new GoodsSkuItems();
				goodsSkuItems.setGoodsId(newGoods.getId());
				goodsSkuItems.setSkuId(newSku.getId());
				goodsSkuItems.setSkuItemsId(newSkuItems.getId());
				goodsSkuItemsList.add(goodsSkuItems);
			}
		}
		
		goodsSkuItemsDAO.batchInsert(goodsSkuItemsList);
		List<GoodsSkuItemsBO> goodsSkuItemsBOList=goodsSkuItemsDAO.queryGoodsSkuItemsBO(newGoods.getId());
		Collection<GoodsSkuItemsVO> GoodsSkuItemsVOlist=oneToManyByGoods(goodsSkuItemsBOList);
		
		List<SkuContent> newSkuContentList=new ArrayList<SkuContent>();
		descartesByGoods(new ArrayList<GoodsSkuItemsVO>(GoodsSkuItemsVOlist), newSkuContentList, 0, "","");;
		
		//skucontents
		List<ChainSkuContent> chainSkuContentList=chainSkuContentDAO.querySkuContent(chainGoods.getId());
		
		for(ChainSkuContent chainSkuContent:chainSkuContentList){
			for(SkuContent skuContent:newSkuContentList){
				if(skuContent.getStandards().equals(skuContent.getStandards())){
					skuContent.setGoodsId(newGoods.getId());
					skuContent.setStock(chainSkuContent.getStock());
					skuContent.setPrice(chainSkuContent.getPrice());
					skuContent.setStatus(Is.YES.toIntValue());
				}
			}
		}
		
		skuContentDAO.batchInsert(newSkuContentList);
		
		//goods_images
		List<ChainGoodsImages>  chainGoodsImagesList=chainGoodsImagesDAO.findByChainGoodsId(chainGoods.getId());
		
		List<GoodsImages> goodsImagesList=new ArrayList<GoodsImages>();
		for(ChainGoodsImages chainGoodsImages:chainGoodsImagesList){
			GoodsImages goodsImages=new GoodsImages();
			BeanUtils.copyProperties(chainGoodsImages, goodsImages);
			goodsImages.setGoodsId(newGoods.getId());
			//FileCopyUtils.copy(new File(chainGoodsPath+chainGoodsImages.getFileName()), new File(goodsPath+goodsImages.getFileName()));
			AliyunOSSClientUtil.moveFile("nengji-prod", chainGoodsImages.getFileName(), goodsPath, chainGoodsPath);
			goodsImagesList.add(goodsImages);
		}
		goodsImagesDAO.batchInsert(goodsImagesList);
		
		ShopChainGoods shopChainGoods=new ShopChainGoods();
		shopChainGoods.setChainGoodsId(chainGoods.getId());
		shopChainGoods.setGoodsId(newGoods.getId());
		shopChainGoods.setShopId(shop.getId());
		shopChainGoodsDAO.insert(shopChainGoods);
		
		
		return result;
	}
	
	
	private Type addType(Type type){
		Type resultType=new Type();
		
		int count = typeDAO.getTypeExist(type);
		if (count > 0) {
			resultType=typeDAO.getType(type);
		}else{
			String parentId = type.getParentId();
			String code = typeDAO.getMaxCode(parentId);
			code = getTypeCode(code);

			String name = type.getName();
			String fullCode = null;
			String fullName = null;
			int level = 1;
			int sort = 1;

			if (Constants.ROOT_VALUE.equals(parentId)) {
				fullName = name;
				level = 1;
				fullCode = typeDAO.getMaxFullCode(Constants.ROOT_VALUE);
				fullCode = getTypeFullCode(OrderNumberUtils.TYPE_NUMBER_PREFIX, fullCode);
				sort = typeDAO.getMaxSort(Constants.ROOT_VALUE) + Constants.TYPE_SORT_ONE;
			} else {
				Type parentType = typeDAO.query(parentId);
				String parentfullName = parentType.getFullName();

				String maxcode = typeDAO.getMaxFullCode(parentId);
				fullCode = parentType.getFullCode() + getTypeFullCode(OrderNumberUtils.TYPE_NUMBER_PREFIX, maxcode);

				sort = typeDAO.getMaxSort(parentId) + Constants.TYPE_SORT_ONE;

				if (StringUtils.isBlank(parentfullName)) {
					throw new TypeNotFoundException("顶级类未找到");
				}

				fullName = parentfullName + Constants.TYPE_FULLNAME_SEPARATOR + name;

				int parentlevel = parentType.getLevel();
				if (parentlevel <= 2) {
					level = parentlevel + 1;
				}

			}

			type.setCode(code);
			type.setFullCode(fullCode);
			type.setLevel(level);
			type.setFullName(fullName);
			type.setSort(sort);

			resultType = typeDAO.insert(type);
		}
		
		return resultType;
	}
	
	private String getTypeCode(String maxCode) {
		int codeValue = 1;
		if (StringUtils.isNotBlank(maxCode)) {
			int currentMaxCode = Integer.valueOf(maxCode);
			codeValue += currentMaxCode;
		}
		String code = OrderNumberUtils.getSystemCode("", codeValue);
		return code;
	}

	private String getTypeFullCode(String prefix, String maxCode) {
		int codeValue = 1;
		if (StringUtils.isNotBlank(maxCode)) {
			int currentMaxCode = Integer.valueOf(maxCode.substring(maxCode.length() - 3, maxCode.length()));
			codeValue += currentMaxCode;
		}
		String code = OrderNumberUtils.getSystemCode(prefix, codeValue);
		return code;
	}
	
	//笛卡尔积公式
	private void descartesByGoods(List<GoodsSkuItemsVO> dimvalue, List<SkuContent> result, int layer, String curstring,String curstandard)
    {
        //大于一个集合时：
        if (layer < dimvalue.size() - 1)
        {
            //大于一个集合时，第一个集合为空
            if (dimvalue.get(layer).getChildrens().size() == 0){
            	descartesByGoods(dimvalue, result, layer + 1, curstring,curstandard);
            }else{
                for (int i = 0; i < dimvalue.get(layer).getChildrens().size(); i++)
                {
                	GoodsSkuItemsDetailVO gv=dimvalue.get(layer).getChildrens().get(i);
                	
                    StringBuilder str = new StringBuilder();
                	str.append(curstring);
                    str.append(gv.getSkuItemsId());
                    
                    StringBuilder str2=new StringBuilder();
                    str2.append(curstandard);
                    str2.append(gv.getStandard());
                    
                    descartesByGoods(dimvalue, result, layer + 1, str.toString(),str2.toString());
                }
            }
        }
        //只有一个集合时：
        else if (layer == dimvalue.size() - 1){
        	
            //只有一个集合，且集合中没有元素
            if (dimvalue.get(layer).getChildrens().size() == 0){
            	SkuContent skuContent=new SkuContent();
            	skuContent.setKey(curstring);
            	skuContent.setStandards(curstandard);
            	result.add(skuContent);
            }
            //只有一个集合，且集合中有元素时：其笛卡尔积就是这个集合元素本身
            else{
                for (int i = 0; i < dimvalue.get(layer).getChildrens().size(); i++){
                	GoodsSkuItemsDetailVO gv=dimvalue.get(layer).getChildrens().get(i);
                	
                	StringBuilder str=new StringBuilder();
                	if(StringUtils.isNotBlank(curstring)){
                		str.append(curstring);
                		str.append("_");
                	}
                	str.append(gv.getSkuItemsId());
                	
                	StringBuilder str2=new StringBuilder();
                	if(StringUtils.isNotBlank(curstandard)){
                		str2.append(curstandard);
                		str2.append("+");
                	}
                	str2.append(gv.getStandard());
                	
                	
                	
                	SkuContent skuContent=new SkuContent();
                	skuContent.setKey(str.toString());
                	skuContent.setStandards(str2.toString());
                	result.add(skuContent);
                }
            }
            
            
            
        }
    }
	
	private Collection<GoodsSkuItemsVO> oneToManyByGoods(List<GoodsSkuItemsBO> goodsSkuItemsBOList){
		
		Map<String, GoodsSkuItemsVO> map = new LinkedHashMap<String, GoodsSkuItemsVO>();
		
		for (GoodsSkuItemsBO bo : goodsSkuItemsBOList) {
			GoodsSkuItemsVO rbo = map.get(bo.getSkuId());
	        if (rbo==null) {
	        	rbo = new GoodsSkuItemsVO();
	        	rbo.setName(bo.getName());
	        	rbo.setSkuId(bo.getSkuId());
	            List<GoodsSkuItemsDetailVO> childrens = new ArrayList<GoodsSkuItemsDetailVO>();
	            rbo.setChildrens(childrens);
	            map.put(bo.getSkuId(),rbo);
	        }
	        
	        GoodsSkuItemsDetailVO goodsSkuItemsDetailVO=new GoodsSkuItemsDetailVO();
	        goodsSkuItemsDetailVO.setSkuItemsId(bo.getSkuItemsId());
	        goodsSkuItemsDetailVO.setStandard(bo.getStandard());
	        rbo.getChildrens().add(goodsSkuItemsDetailVO);
	    }
		Collection<GoodsSkuItemsVO> data = map.values();
		
		return data;
	}
	
	
	/**
	 * 
	 * TODO
	 * @author FEB
	 * @time 2018年6月28日 下午2:15:40
	 * @return Collection<ChainGoodsSkuItemsVO>
	 */
	private Collection<ChainGoodsSkuItemsVO> oneToManyByChainGoods(List<ChainGoodsSkuItemsBO> chainGoodsSkuItemsBOList){
		
		Map<String, ChainGoodsSkuItemsVO> map = new LinkedHashMap<String, ChainGoodsSkuItemsVO>();
		
		for (ChainGoodsSkuItemsBO bo : chainGoodsSkuItemsBOList) {
			ChainGoodsSkuItemsVO rbo = map.get(bo.getChainSkuId());
	        if (rbo==null) {
	        	rbo = new ChainGoodsSkuItemsVO();
	        	rbo.setName(bo.getName());
	        	rbo.setChainSkuId(bo.getChainSkuId());
	            List<ChainGoodsSkuItemsDetailVO> childrens = new ArrayList<ChainGoodsSkuItemsDetailVO>();
	            rbo.setChildrens(childrens);
	            map.put(bo.getChainSkuId(),rbo);
	        }
	        
	        ChainGoodsSkuItemsDetailVO chainGoodsSkuItemsDetailVO=new ChainGoodsSkuItemsDetailVO();
	        chainGoodsSkuItemsDetailVO.setChainSkuItemsId(bo.getChainSkuItemsId());
	        chainGoodsSkuItemsDetailVO.setStandard(bo.getStandard());
	        rbo.getChildrens().add(chainGoodsSkuItemsDetailVO);
	    }
		Collection<ChainGoodsSkuItemsVO> data = map.values();
		return data;
	}
	
	@Override
	public ResultVO editStatus(ChainGoodsEditVO chainGoodsEditVO) {
		ResultVO result = new ResultVO();
		Integer status = chainGoodsEditVO.getStatus();
		if (status != GoodsStatus.AUDITSUCCESS.toIntStatus() && status != GoodsStatus.AUDITFAIL.toIntStatus()) {
			return result;
		}

		boolean data = false;
		if (status == GoodsStatus.AUDITSUCCESS.toIntStatus()) {
			data = chainGoodsDAO.updateStatus(chainGoodsEditVO.getId(), GoodsStatus.AUDITSUCCESS.toIntStatus());
		} else if (status == GoodsStatus.AUDITFAIL.toIntStatus()) {
			data = chainGoodsDAO.updateStatus(chainGoodsEditVO.getId(), GoodsStatus.AUDITFAIL.toIntStatus());
		}
		if(chainGoodsEditVO.getAuditFailDescription() != null){
			ChainGoods chainGoods=chainGoodsDAO.query(chainGoodsEditVO.getId());
			chainGoods.setAuditFailDescription(chainGoodsEditVO.getAuditFailDescription());
			chainGoodsDAO.update(chainGoods);
		}
		result.setData(data);

		return result;
	}
	
	@Override
	public ResultVO batchEditStatus(String[] ids, Integer status,String auditFailDescription) {
		ResultVO result = new ResultVO();
		if (ids.length <= 0) {
			return result;
		}

		if (status != GoodsStatus.AUDITSUCCESS.toIntStatus() && status != GoodsStatus.AUDITFAIL.toIntStatus()) {
			return result;
		}
		boolean data = false;
		if (status == GoodsStatus.AUDITSUCCESS.toIntStatus()) {
			data = chainGoodsDAO.batchUpdateStatus(ids, GoodsStatus.AUDITSUCCESS.toIntStatus());
		} else if (status == GoodsStatus.AUDITFAIL.toIntStatus()) {
			data = chainGoodsDAO.batchUpdateStatus(ids, GoodsStatus.AUDITFAIL.toIntStatus());
		}
		for(int i=0;i<ids.length;i++){
			ChainGoods chainGoods=chainGoodsDAO.query(ids[i]);
			chainGoods.setAuditFailDescription(auditFailDescription);
			chainGoodsDAO.update(chainGoods);
		}	
		result.setData(data);
		return result;
	}
	
	@Override
	public ResultVO updateGoodsStatus(String id,String auditFailDescription) {
		ResultVO result = new ResultVO();
		ChainGoods chainGoods=chainGoodsDAO.query(id);
		ModulesGoods modulesGoods=modulesGoodsDAO.query(id);
		if(chainGoods == null){
			throw new ChainGoodsNotFoundException("商品不存在");
		}
		
		if (chainGoods.getStatus() != GoodsStatus.ACTIVE.toIntStatus()) {
			throw new GoodsStatusErrorException("商品不为上架状态");
		}
		if(StringUtils.isNotBlank(auditFailDescription)){
			chainGoods.setStatus(GoodsStatus.AUDITFAIL.toIntStatus());
			chainGoods.setAuditFailDescription(auditFailDescription);
		}
		chainGoodsDAO.update(chainGoods);
		
		if(modulesGoods != null){
			modulesGoods.setStatus(GoodsStatus.AUDITFAIL.toIntStatus());
			modulesGoodsDAO.update(modulesGoods);
		}
		
		return result;
	}

	@Override
	public ResultVO batchImportChainGoods(String[] ids,String sessionId) {
		ResultVO result=new ResultVO();
		for(String id:ids){
			ChainGoodsTransformVO chainGoodsTransformVO=new ChainGoodsTransformVO();
			chainGoodsTransformVO.setId(id);
			chainGoodsTransformVO.setSessionId(sessionId);
			importChainGoods(chainGoodsTransformVO);
		}
		return result;
	}
	
}
